#include "StdAfx.h"
#include <windows.h>
#include <fstream>
#include "log.h"

const char DIVIDER[10] = { 13, 10, '-', '-', '-', '-', '-', '-', 13, 10 };
const char CrLf[3]	   = { 13, 10, 0 };

const char LOG_FILENAME[] = "C:\\Dbg.log";	// Default log-file name

CLog debug;

CLog::CLog ()
{	
	// Save old log file (up to 2)
	char newFile1[255];
	char newFile2[255];

	lstrcpy( newFile1, LOG_FILENAME );
	lstrcat( newFile1, "~" );

	lstrcpy( newFile2, newFile1 );
	lstrcat( newFile2, "~" );

	CopyFile( newFile1,     newFile2, FALSE );
	CopyFile( LOG_FILENAME, newFile1, FALSE );

	m_file.open(LOG_FILENAME, std::ios::out | std::ios::app);
}

CLog::~CLog ()
{
	CloseLog();
}

void CLog::CloseLog ()
{
	m_file.close();
}

void CLog::log( CLog::LogLevel level, const char *fmt, ... )
{
	m_Lock.lock();

	DWORD threadID = GetCurrentThreadId();
	// Format string
	char buffer[1024*50];
	va_list arglist;
	va_start( arglist, fmt );
	wvsprintf( buffer, fmt, arglist );
	va_end(arglist);

	// Format time stamp
	char  buf[256];

	SYSTEMTIME time;
	GetLocalTime(&time);

	char logLevel;
	switch(level)
	{
	case CLog::Error:
		logLevel = 'E';
		break;
	case CLog::Warning:
		logLevel = 'W';
		break;
	case CLog::Info:
		logLevel = 'I';
		break;
	default:
		break;
	}

	wsprintf( buf, "%d %c %02d/%02d/%02d %02d:%02d:%02d ", 
					threadID, logLevel,
					time.wMonth, time.wDay,    time.wYear,
					time.wHour,  time.wMinute, time.wSecond);
	
	m_file<<buf<<buffer<<endl;

	m_Lock.unlock();
}

void CLog::ShowLastError() 
{
	char* lpMsgBuf;

	FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,    
		NULL,
		GetLastError(),
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
		(LPTSTR) &lpMsgBuf,    
		0,    
		NULL );

	int len = lstrlen(lpMsgBuf)-1;

	if ( len>0 )
	{
		while ( len>=0 && (lpMsgBuf[len]==0x0d || lpMsgBuf[len]==0x0a) )
			len--;
		lpMsgBuf[len+1] = 0; 
		log( CLog::Error, "GetLastError(): %s", (char*)lpMsgBuf );
		LocalFree( lpMsgBuf ); // Free the buffer.
	}
}
